package com.sc.socket.tcpdemo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author shuc001
 * @Date 2019-02-01 21:18
 */
public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(2000);
        System.out.println("服务器启动");

        //等待连接
        for(;;){
            Socket client = server.accept();
            if(client!=null){
                ClientHandle clientHandle = new ClientHandle(client);
                clientHandle.start();
            }
        }

    }

    private static class ClientHandle extends Thread{
        private Socket socket;
        private boolean flag = true;

        ClientHandle(Socket socket){
            this.socket = socket;
        }

        @Override
        public void run() {
            System.out.println("客户端连接"+socket.getPort());
            try {
                    PrintStream socketOutput = new PrintStream(socket.getOutputStream());
                    BufferedReader socketInput  = new BufferedReader(
                            new InputStreamReader(socket.getInputStream()));
                do{
                    String str = socketInput.readLine();
                    if(str.equalsIgnoreCase("bye")){
                        socketOutput.println(str);
                        flag=false;
                    }else{
                        System.out.println(str);
                        socketOutput.println("reply "+str);
                    }
                }while (flag);
                socketInput.close();
                socketOutput.close();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("客户端断开");
        }
    }
}
